//
//  FacesCountSensor.m
//  Pennyworth
//
//  Created by Chris Karr on 7/5/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "FacesCountSensor.h"
#import "Context.h"

#import "SensorsController.h"

#include <OpenCV/OpenCV.h>

#define SENSOR_NAME @"Face Count"

@implementation FacesCountSensor

@synthesize timer;

- (void) scan:(NSTimer *) theTimer
{
	if (![[SensorsController sharedController] canFire:SENSOR_NAME])
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:SENSOR_NAME forKey:OBSERVATION_SENSOR];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		
		return;
	}		
	
	BOOL go = [testCamera startWithSize:NSMakeSize (640, 480)];
	
	if (!go)
		return;

	[testCamera stop];

	NSString * haarPath = [[NSBundle mainBundle] pathForResource:@"haar" ofType:@"xml"];

	CvCapture * camera = cvCaptureFromCAM (CV_CAP_ANY);

	if (camera == NULL)
		return;
	else
	{
		CvMemStorage * storage = cvCreateMemStorage (0);

		CvHaarClassifierCascade * cascade = (CvHaarClassifierCascade *) cvLoad ([haarPath UTF8String], 0, 0, 0);

		if (cascade == NULL)
			return;
		else
		{
			IplImage * current_frame = cvQueryFrame (camera);

			CvSeq * faces = cvHaarDetectObjects (current_frame, cascade, storage, 1.1, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize (30, 30));

			if (faces != NULL)
			{
				NSMutableDictionary * note = [NSMutableDictionary dictionary];
		
				[note setValue:@"Face Count" forKey:OBSERVATION_SENSOR];
				[note setValue:[NSNumber numberWithInt:faces->total] forKey:OBSERVATION_OBSERVATION];
				[note setValue:[NSNumber numberWithInteger:60] forKey:OBSERVATION_LIFESPAN];
					
				[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
			}

			cvReleaseHaarClassifierCascade (&cascade);
		}
		
		cvReleaseMemStorage (&storage);
		
		cvReleaseCapture (&camera);
	}
}

- (void) awakeFromNib
{
	[[SensorsController sharedController] addSensor:SENSOR_NAME];
	
	testCamera = [[CSGCamera alloc] init];

	self.timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(scan:) userInfo:nil repeats:YES];
	
	[self.timer fire];
}

@end
